"""
主题: 线程间通信
问题: 你的程序中有多个线程，你需要在这些线程之间安全地交换信息或数据
提示 : 
"""

from queue import Queue
from threading import Thread
import time


# Object that signals shutdown
_sentinel = object()

# A thread that produces data
def producer(out_q):
    n = 10
    while n > 0:
        # Produce some data
        out_q.put(n)
        print('Put:', n)
        time.sleep(1)
        n -= 1


    # Put the sentinel on the queue to indicate completion
    out_q.put(_sentinel)
    print('Producer shutting down')

# A thread that consumes data
def consumer(in_q):
    while True:
        # Get some data
        data = in_q.get()

        # Check for termination
        if data is _sentinel:
            in_q.put(_sentinel) # 关闭其他消费者
            break

        # Process the data
        print('Got:', data)
        time.sleep(1.2)

    print('Consumer shutting down')

def recipe1():
    q = Queue()
    t1 = Thread(target=consumer, args=(q,))
    t2 = Thread(target=producer, args=(q,))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

def main():
    print('recipe1'.center(20, '*'))
    recipe1()



if __name__ == '__main__':
    main()       